import blue
import uthread
import util
import xtriui
import uix
import form
import dbg
import log
import listentry
import uicls
import uiconst

class CorpApplications(uicls.Container):
    __guid__ = 'form.CorpApplications'
    __nonpersistvars__ = []

    def Load(self, args):
        if not self.sr.Get('inited', 0):
            self.sr.corpTabInfo = [[mls.UI_CORP_NEW,
              const.crpApplicationAppliedByCharacter,
              'corpapplications_new']]
            self.sr.myTabInfo = [[mls.UI_CORP_APPLIED,
              const.crpApplicationAppliedByCharacter,
              'myapplications_new']]
            self.sr.inited = 1
            self.sr.viewingOwnerID = None
            self.sr.viewingStatus = None
            self.sr.scroll = uicls.Scroll(name='applications', parent=self, padding=(const.defaultPadding,
             const.defaultPadding,
             const.defaultPadding,
             const.defaultPadding))
            self.sr.scroll.multiSelect = 0
            tabs = []
            if (const.corpRolePersonnelManager & eve.session.corprole):
                tabs = [[mls.UI_GENERIC_CORPORATE,
                  self,
                  self,
                  'corporate']]
            tabs.append([mls.UI_CORP_MYAPPLICATIONS,
             self,
             self,
             'myApplications'])
            self.sr.tabs = form.TabGroup(uicls.Container(name='tabparent', align=uiconst.TOTOP, height=18, parent=self, idx=0)).Startup(tabs, 'corporationApplications')
        sm.GetService('corpui').LoadTop('07_08', mls.UI_CORP_APPLICATIONS)
        self.sr.viewingStatus = 0
        if args.startswith('corporate'):
            self.sr.viewingOwnerID = eve.session.corpid
            self.ShowCorporateApplications()
        elif args.startswith('myApplications'):
            self.sr.viewingOwnerID = eve.session.charid
            self.ShowMyApplications()
        elif not args.startswith('applications'):
            self.sr.viewingOwnerID = None



    def WithdrawApplications(self, *args):
        selected = self.sr.scroll.GetSelected()
        if not len(selected):
            return 
        for entry in selected:
            application = entry.application
            if ((eve.session.charid != application.characterID) or (eve.session.corpid != application.corporationID)):
                self.WithdrawApplication(application.characterID, application.corporationID)




    def ShowCorporateApplications(self):
        uix.LogInfo('ShowCorporateApplications')
        self.sr.scroll.sr.id = 'corpApplications_scroll'
        try:
            sm.GetService('corpui').ShowLoad()
            scrolllist = []
            headers = []
            hint = mls.UI_CORP_HINT3
            if ((const.corpRolePersonnelManager & eve.session.corprole) != const.corpRolePersonnelManager):
                uix.LogInfo('ShowCorporateApplications Invalid Callee')
                hint = mls.UI_CORP_HINT23
            elif ((self is None) or self.destroyed):
                uix.LogInfo('ShowCorporateApplications Destroyed or None')
                hint = '\xfe\xfa s\xe1st mig ekki.'
            else:
                uix.LogInfo('ShowCorporateApplications status', self.sr.viewingStatus)
                headers = [mls.UI_GENERIC_NAME,
                 mls.UI_GENERIC_STATUS,
                 mls.UI_GENERIC_DATE]
                applications = sm.GetService('corp').GetApplicationsWithStatus(self.sr.viewingStatus)
                uix.LogInfo('ShowCorporateApplications len(applications):', len(applications))
                owners = []
                for application in applications:
                    if (application.characterID not in owners):
                        owners.append(application.characterID)

                if len(owners):
                    cfg.eveowners.Prime(owners)
                for application in applications:
                    self._CorpApplications__AddApplicationToList(application, scrolllist)

            if scrolllist:
                self.sr.scroll.Load(fixedEntryHeight=19, contentList=scrolllist, headers=headers)
                self.SetHint(None)
            else:
                self.sr.scroll.Load(fixedEntryHeight=19, contentList=scrolllist, headers=[])
                self.SetHint(hint)

        finally:
            sm.GetService('corpui').HideLoad()




    def ShowMyApplications(self):
        uix.LogInfo('ShowMyApplications')
        self.sr.scroll.sr.id = 'myApplications_scroll'
        try:
            sm.GetService('corpui').ShowLoad()
            scrolllist = []
            headers = []
            hint = mls.UI_CORP_HINT3
            if ((self is None) or self.destroyed):
                uix.LogInfo('ShowMyApplications Destroyed or None')
            else:
                uix.LogInfo('ShowMyApplications status', self.sr.viewingStatus)
                headers = [mls.UI_GENERIC_NAME,
                 mls.UI_GENERIC_STATUS,
                 mls.UI_GENERIC_DATE]
                applications = sm.GetService('corp').GetMyApplicationsWithStatus(self.sr.viewingStatus)
                uix.LogInfo('ShowMyApplications len(applications):', len(applications))
                owners = []
                for application in applications:
                    if (application.corporationID not in owners):
                        owners.append(application.corporationID)

                if len(owners):
                    cfg.eveowners.Prime(owners)
                for application in applications:
                    self._CorpApplications__AddApplicationToList(application, scrolllist)

            if scrolllist:
                self.sr.scroll.Load(fixedEntryHeight=19, contentList=scrolllist, headers=headers)
                self.SetHint(None)
            else:
                self.sr.scroll.Load(fixedEntryHeight=19, contentList=scrolllist, headers=[])
                self.SetHint(hint)

        finally:
            sm.GetService('corpui').HideLoad()




    def __AddApplicationToList(self, application, scrolllist):
        if (application.status != self.sr.viewingStatus):
            return 
        isMine = (self.sr.viewingOwnerID == eve.session.charid)
        status = ''
        if (application.status == const.crpApplicationAppliedByCharacter):
            status = mls.UI_CORP_UNPROCESSED
        data = util.KeyVal()
        data.statusLabel = status
        data.isMine = isMine
        data.GetMenu = self.GetApplicationMenu
        data.corporation = sm.GetService('corp').GetCorporation(application.corporationID)
        data.application = application
        if isMine:
            data.label = ('%s<t>%s<t>%s' % (data.corporation.corporationName,
             status,
             util.FmtDate(application.applicationDateTime, 'ls')))
            data.OnDblClick = lambda *args: self.ViewApplication(application.corporationID)
        else:
            data.label = ('%s<t>%s<t>%s' % (cfg.eveowners.Get(application.characterID).name,
             status,
             util.FmtDate(application.applicationDateTime, 'ls')))
            data.OnDblClick = lambda *args: self.CorpViewApplication(application.characterID, application.applicationText)
        scrolllist.append(listentry.Get('Generic', data=data))



    def GetApplicationMenu(self, entry):
        isMine = entry.sr.node.isMine
        application = entry.sr.node.application
        corporation = entry.sr.node.corporation
        status = entry.sr.node.statusLabel
        menu = []
        if isMine:
            withdraw = None
            menu.append((mls.UI_CMD_VIEWAPPLICATION,
             self.ViewApplication,
             (application.corporationID)))
            if not ((eve.session.charid == application.characterID) and (eve.session.corpid == application.corporationID)):
                menu.append((mls.UI_CMD_WITHDRAW,
                 self.WithdrawApplication,
                 (application.characterID, corporation.corporationID)))
        else:
            menu.extend([(mls.UI_CMD_VIEWAPPLICATION,
              self.CorpViewApplication,
              (application.characterID, application.applicationText)),
             (mls.UI_CMD_ACCEPT,
              self.AcceptOrRejectApplication,
              (application.characterID,
               '',
               const.crpApplicationAcceptedByCorporation)),
             (mls.UI_CMD_REJECT,
              self.AcceptOrRejectApplication,
              (application.characterID,
               '',
               const.crpApplicationRejectedByCorporation))])
            menu.append(None)
            menu.append((mls.UI_CMD_SHOWINFO,
             self.ShowInfo,
             (cfg.eveowners.Get(application.characterID).typeID, application.characterID)))
            menu.extend(sm.GetService('menu').CharacterMenu(application.characterID))
        return menu



    def ShowInfo(self, typeID, itemID, *args):
        sm.GetService('info').ShowInfo(typeID, itemID)



    def SetHint(self, hintstr = None):
        self.sr.scroll.ShowHint(hintstr)



    def GetEntry(self, applicantID, corporationID):
        for entry in self.sr.scroll.GetNodes():
            if ((entry is None) or (entry is None)):
                continue
            if ((entry.panel is None) or entry.panel.destroyed):
                continue
            if ((entry.application.characterID == applicantID) and (entry.corporation.corporationID == corporationID)):
                return entry




    def OnCorporationApplicationChanged(self, applicantID, corporationID, change):
        uix.LogInfo('OnCorporationApplicationChanged applicantID', applicantID, 'corporationID', corporationID, 'change', change)
        if ((self is None) or self.destroyed):
            uix.LogInfo('OnCorporationApplicationChanged self is None or self.destroyed')
            return 
        if ((not self.sr.Get('scroll')) or (self.sr.scroll is None)):
            uix.LogInfo('OnCorporationApplicationChanged no scroll')
            return 
        bAdd = 1
        bRemove = 1
        for (old, new,) in change.itervalues():
            if ((old is None) and (new is None)):
                continue
            if (old is not None):
                bAdd = 0
            if (new is not None):
                bRemove = 0

        if (bAdd and bRemove):
            raise RuntimeError('applications::OnCorporationApplicationChanged WTF')
        application = None
        if not bRemove:
            if (eve.session.charid == applicantID):
                application = sm.GetService('corp').GetMyApplications(corporationID, forceUpdate=True)
            else:
                application = sm.GetService('corp').GetApplications(applicantID, forceUpdate=True)
            if (application is not None):
                status = application.status
                if (applicantID == eve.session.charid):
                    self.sr.tabs.BlinkPanelByName(mls.UI_CORP_MYAPPLICATIONS)
                else:
                    if (corporationID == eve.session.corpid):
                        self.sr.tabs.BlinkPanelByName(mls.UI_GENERIC_CORPORATE)
        if ('status' in change):
            activeTab = self.sr.tabs.GetSelectedArgs()
            if (self.sr.viewingStatus in change['status']):
                (oldStatus, newStatus,) = change['status']
                if (newStatus != self.sr.viewingStatus):
                    bRemove = True
                if (newStatus == self.sr.viewingStatus):
                    bAdd = True
                if (bRemove or bAdd):
                    if (self.sr.viewingOwnerID == eve.session.charid):
                        self.Load('myApplications')
                    else:
                        if (self.sr.viewingOwnerID == eve.session.corpid):
                            self.Load('corporate')



    def WithdrawApplication(self, charid, corpid, *args):
        try:
            sm.GetService('corpui').ShowLoad()
            sm.GetService('corp').DeleteApplication(corpid, charid)

        finally:
            sm.GetService('corpui').HideLoad()




    def ViewApplication(self, corporationID, application = None):
        if (application is None):
            application = sm.GetService('corp').GetMyApplications(corporationID)
        if (application is None):
            return 
        format = []
        status = mls.UI_CORP_HINT24
        format.append({'type': 'text',
         'text': (mls.UI_CORP_YOURAPPLICATIONTOJOIN % {'corp': cfg.eveowners.Get(application.corporationID).name})})
        format.append({'type': 'push'})
        format.append({'type': 'bbline'})
        format.append({'type': 'labeltext',
         'label': mls.UI_GENERIC_STATUS,
         'text': status,
         'frame': 1})
        format.append({'type': 'bbline'})
        format.append({'type': 'push',
         'frame': 1})
        if ((application.applicationText is not None) and len(application.applicationText)):
            format.append({'type': 'text',
             'text': application.applicationText,
             'frame': 1})
        else:
            format.append({'type': 'text',
             'text': ' ',
             'frame': 1})
        format.append({'type': 'push',
         'frame': 1})
        format.append({'type': 'bbline'})
        btn = uix.OK
        left = ((eve.triapp.uilib.desktop.width / 2) - (400 / 2))
        top = ((eve.triapp.uilib.desktop.height / 2) - (400 / 2))
        retval = uix.HybridWnd(format, mls.UI_CORP_VIEWAPPLICATIONDETAILS, 1, None, btn, [left, top], 400, icon='07_06')



    def CheckApplication(self, retval):
        if retval.has_key('appltext'):
            applicationText = retval['appltext']
            if (len(applicationText) > 1000):
                return (mls.UI_CORP_HINT4 % {'len': str(len(applicationText))})
            return ''



    def AcceptOrRejectApplication(self, characterID, applicationText, status):
        sm.GetService('corp').UpdateApplicationOffer(characterID, applicationText, status)



    def CorpViewApplication(self, characterID, applicationText = ''):
        corporationID = eve.session.corpid
        if ((const.corpRolePersonnelManager & eve.session.corprole) != const.corpRolePersonnelManager):
            return 
        stati = {}
        format = []
        stati[const.crpApplicationRejectedByCorporation] = (mls.UI_CMD_REJECT, 1)
        stati[const.crpApplicationAcceptedByCorporation] = (mls.UI_CMD_ACCEPT, 0)
        format.append({'type': 'push'})
        format.append({'type': 'text',
         'text': ('%s: <b>%s</b><br>' % (mls.UI_GENERIC_FROM, cfg.eveowners.Get(characterID).name))})
        format.append({'type': 'push'})
        format.append({'type': 'bbline'})
        i = 1
        for key in stati:
            if (i == 1):
                lbl = mls.UI_GENERIC_STATUS
            else:
                lbl = ''
            (text, selected,) = stati[key]
            format.append({'type': 'checkbox',
             'setvalue': selected,
             'key': key,
             'label': lbl,
             'text': text,
             'frame': 1,
             'group': 'stati'})
            i = 0

        format.append({'type': 'bbline'})
        format.append({'type': 'push',
         'frame': 1})
        format.append({'type': 'textedit',
         'setvalue': applicationText,
         'key': 'appltext',
         'label': mls.UI_GENERIC_MESSAGE,
         'required': 0,
         'frame': 1,
         'readonly': 1})
        format.append({'type': 'errorcheck',
         'errorcheck': self.CheckApplication})
        format.append({'type': 'push',
         'frame': 1})
        format.append({'type': 'bbline'})
        btn = uix.OKCANCEL
        left = ((eve.triapp.uilib.desktop.width / 2) - (400 / 2))
        top = ((eve.triapp.uilib.desktop.height / 2) - (400 / 2))
        retval = uix.HybridWnd(format, mls.UI_CORP_VIEWAPPLICATIONDETAILS, 1, None, btn, [left, top], 400)
        if (retval is not None):
            applicationText = retval['appltext']
            status = retval['stati']
            sm.GetService('corp').UpdateApplicationOffer(characterID, applicationText, status)




